/*
 * @Author: XPectuer
 * @LastEditor: XPectuer
 */
package main

import (
	"database/sql"
	"fmt"
	"sync"

	_ "github.com/mattn/go-sqlite3"
	"github.com/sirupsen/logrus"
)

var db *sql.DB
var once sync.Once

func initDB() {
	logrus.Info("Init DB")
	dbt, err := sql.Open("sqlite3", "./54.sqlite3")
	if err != nil {
		logrus.Fatal("Cannot Open Databse", err)
	}

	initQuery := `CREATE TABLE IF NOT EXISTS users (
		id INTEGER PRIMARY KEY AUTOINCREMENT,
		uuid TEXT NOT NULL UNIQUE,
		nickName TEXT NOT NULL UNIQUE,
		wordCount LONG NOT NULL
	);`

	dbt.Exec(initQuery)
	db = dbt
}
func InitDB() *sql.DB {
	once.Do(initDB)
	return db
}

func QueryUserByUUID(db *sql.DB, uuid string) (*User, error) {
	var u User
	query := `SELECT uuid, nickName, wordCount FROM users WHERE uuid = ?;`
	err := db.QueryRow(query, uuid).Scan(&u.Uuid, &u.NickName, &u.wordCount)
	if err != nil {
		return nil, err
	}

	return &u, nil
}

func UpdateWordCount(db *sql.DB, user *User) (sql.Result, error) {
	return UpdateWordCountByUUID(db, user.Uuid, int(user.wordCount))
}
func UpdateWordCountByUUID(db *sql.DB, uuid string, newWordCount int) (sql.Result, error) {
	stmt := `UPDATE users SET wordCount = ? WHERE uuid = ?`

	result, err := db.Exec(stmt, newWordCount, uuid)
	if err != nil {
		return nil, fmt.Errorf("failed to update word count: %w", err)
	}

	return result, nil
}

func Insert(db *sql.DB, user *User) (sql.Result, error) {
	// insert user into DB
	uuid := user.Uuid
	nickName := user.NickName
	wordCount := user.wordCount
	stmt := `INSERT INTO users (uuid, nickName, wordCount) VALUES (?, ?, ?)`

	r, err := db.Exec(stmt, uuid, nickName, wordCount)
	if err != nil {
		logrus.WithError(err).Error("Failed to Insert Row.")
		return nil, err
	}

	logrus.Debug(r)
	return r, nil
}
